﻿using CastingWellEquipmentGUI.Config;
using CastingWellEquipmentGUI.Model;
using CastingWellEquipmentGUI.Utils;
using CastingWellEquipmentGUI.ViewModel.Common.Command;
using CastingWellEquipmentGUI.ViewModel.Common.LogTool;
using CastingWellEquipmentGUI.ViewModel.Common.WindowsManager;
using Confluent.Kafka;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows;
using System.Windows.Media;

namespace CastingWellEquipmentGUI.ViewModel.Pages
{
    public class LaunderPageViewModel : ViewModelBase
    {

        #region 变量/常量
        /// <summary>
        /// 当前窗体名称
        /// </summary>
        private const string showPageTitle = "LaunderPage";
        private Control _CurrentControl;
        /// <summary>
        /// 当前选中的控件
        /// </summary>
        public Control CurrentControl
        {
            get { return _CurrentControl; }
            set
            {
                _CurrentControl = value;
                RaisePropertyChanged("CurrentControl");
            }
        }
        #endregion 变量/常量

        #region 页面属性
        /// <summary>
        /// 流槽挡板1
        /// BUG 啥业务逻辑
        /// </summary>
        public double Button_LaunderBaffle1
        {
            get
            {
                double doublValue = 0;
                List<ControlAndWindowTag> controlAndWindowTags = TagTool.GetTagsByFormNameAndControlName(showPageTitle, "Button_LaunderBaffle1", "LaunderBafflePanel");
                foreach (ControlAndWindowTag item in controlAndWindowTags)
                {
                    if (item.WindowControlName == "Button_BaffleLowering")
                    {
                        if (TagTool.GetTagValueById(item.TagId) == "true")
                        {
                            doublValue = 180;
                        }
                    }
                    if (item.WindowControlName == "Button_BaffleRising")
                    {
                        if (TagTool.GetTagValueById(item.TagId) == "true")
                        {
                            doublValue = 0;
                        }
                    }
                }
                return doublValue;
            }
        }
        /// <summary>
        /// 流槽挡板2
        /// BUG 啥业务逻辑
        /// </summary>
        public double Button_LaunderBaffle2
        {
            get
            {
                double doublValue = 0;
                if (showPageTitle != null)
                {
                    List<ControlAndWindowTag> controlAndWindowTags = TagTool.GetTagsByFormNameAndControlName(showPageTitle, "Button_LaunderBaffle2", "LaunderBafflePanel");
                    foreach (ControlAndWindowTag item in controlAndWindowTags)
                    {
                        if (item.WindowControlName == "Button_BaffleLowering")
                        {
                            if (TagTool.GetTagValueById(item.TagId) == "true")
                            {
                                doublValue = 180;
                            }
                        }
                        if (item.WindowControlName == "Button_BaffleRising")
                        {
                            if (TagTool.GetTagValueById(item.TagId) == "true")
                            {
                                doublValue = 0;
                            }
                        }
                    }
                }
                return doublValue;
            }
        }
        /// <summary>
        /// 激光液位计1温度PV
        /// </summary>
        public string Label_LaserLevelGauge1Temperature_PV
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_LaserLevelGauge1Temperature_PV"); }
        }
        /// <summary>
        /// 激光液位计1距离PV
        /// </summary>
        public string Label_LaserLevelGauge1Distance_PV
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_LaserLevelGauge1Distance_PV"); }
        }
        /// <summary>
        /// 激光液位计1距离SP
        /// </summary>
        public string Label_LaserLevelGauge1Distance_SP
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_LaserLevelGauge1Distance_SP"); }
        }
        /// <summary>
        /// 送丝机SP
        /// </summary>
        public string Label_WireFeeder_SP
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_WireFeeder_SP"); }
        }
        /// <summary>
        /// 送丝机PV1
        /// </summary>
        public string Label_WireFeeder_PV1
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_WireFeeder_PV1"); }
        }
        /// <summary>
        /// 送丝机PV2
        /// </summary>
        public string Label_WireFeeder_PV2
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_WireFeeder_PV2"); }
        }
        /// <summary>
        /// 激光液位计2温度PV
        /// </summary>
        public string Label_LaserLevelGauge2Temperature_PV
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_LaserLevelGauge2Temperature_PV"); }
        }
        /// <summary>
        /// 激光液位计2距离PV
        /// </summary>
        public string Label_LaserLeve2Gauge1Distance_PV
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_LaserLeve2Gauge1Distance_PV"); }
        }
        /// <summary>
        /// 激光液位计2距离SP
        /// </summary>
        public string Label_LaserLevelGauge2Distance_SP
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_LaserLevelGauge2Distance_SP"); }
        }
        /// <summary>
        /// 探测器PV1
        /// </summary>
        public string Label_Detector_PV1
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_Detector_PV1"); }
        }
        /// <summary>
        /// 探测器PV2
        /// </summary>
        public string Label_Detector_PV2
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_Detector_PV2"); }
        }
        /// <summary>
        /// 重量
        /// </summary>
        public string Label_Weight_PV1
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_Weight_PV1"); }
        }

        #region 预检测项
        private Visibility _PreDetectionVisibility;
        /// <summary>
        /// 预检测框显隐
        /// </summary>
        public Visibility PreDetectionVisibility
        {
            get { return _PreDetectionVisibility; }
            set
            {
                _PreDetectionVisibility = value;
                RaisePropertyChanged("PreDetectionVisibility");
            }
        }
        /// <summary>
        /// CCF液位检测器
        /// </summary>
        public Brush Label_CCFLiquidLevelDetectorIsNormal
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_CCFLiquidLevelDetectorIsNormal") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// CCF挡板位置
        /// </summary>
        public Brush Label_ThePositionOfCCFBaffleIsNormal
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_ThePositionOfCCFBaffleIsNormal") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 铸盘挡板位置
        /// </summary>
        public Brush Label_ThePositionOfCastingPlateBaffleIsNormal
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_ThePositionOfCastingPlateBaffleIsNormal") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 已选择炉激光液位上限范围
        /// </summary>
        public Brush Label_TheUpperLimitRangeOfLaserLiquidLevelOfTheSelectedFurnaceIsNormal
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_TheUpperLimitRangeOfLaserLiquidLevelOfTheSelectedFurnaceIsNormal") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 已选择炉激光液位下限范围
        /// </summary>
        public Brush Label_TheLowerLimitRangeOfLaserLiquidLevelOfTheSelectedFurnaceIsNormal
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_TheLowerLimitRangeOfLaserLiquidLevelOfTheSelectedFurnaceIsNormal") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 已选择炉激光液位传感器温度
        /// </summary>
        public Brush Label_TheTemperatureOfLaserLiquidLevelSensorOfSelectedFurnaceIsNormal
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_TheTemperatureOfLaserLiquidLevelSensorOfSelectedFurnaceIsNormal") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 已选择炉激光液位传感器信号有效
        /// </summary>
        public Brush Label_TheLaserLiquidLevelSensorSignalOfTheSelectedFurnaceIsValid
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_TheLaserLiquidLevelSensorSignalOfTheSelectedFurnaceIsValid") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 铸盘激光液位上限范围
        /// </summary>
        public Brush Label_TheUpperLimitRangeOfLaserLiquidLevelOfCastingDiscIsNormal
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_TheUpperLimitRangeOfLaserLiquidLevelOfCastingDiscIsNormal") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 铸盘激光液位下限范围
        /// </summary>
        public Brush Label_TheLowerLimitRangeOfLaserLiquidLevelOfCastingDiscIsNormal
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_TheLowerLimitRangeOfLaserLiquidLevelOfCastingDiscIsNormal") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 铸盘激光液位传感器温度
        /// </summary>
        public Brush Label_TheTemperatureOfTheLaserLiquidLevelSensorOfTheCastingDiscIsNormal
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_TheTemperatureOfTheLaserLiquidLevelSensorOfTheCastingDiscIsNormal") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 铸盘激光液位传感器信号有效
        /// </summary>
        public Brush Label_TheSignalOfTheLaserLiquidLevelSensorOfTheCastingPlateIsValid
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_TheSignalOfTheLaserLiquidLevelSensorOfTheCastingPlateIsValid") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 已选择炉液位探头
        /// </summary>
        public Brush Label_TheSelectedFurnaceLiquidLevelProbeIsNormal
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_TheSelectedFurnaceLiquidLevelProbeIsNormal") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 铸盘挡板处液位检测
        /// </summary>
        public Brush Label_TheLiquidLevelDetectionAtTheBaffleOfTheCastingPlateIsNormal
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_TheLiquidLevelDetectionAtTheBaffleOfTheCastingPlateIsNormal") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 流槽挡板气源压力
        /// </summary>
        public Brush Label_TheAirSupplyPressureOfLaunderBaffleIsNormal
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_TheAirSupplyPressureOfLaunderBaffleIsNormal") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 流程铝水温度
        /// </summary>
        public Brush Label_TheTemperatureOfMoltenAluminumInTheProcessIsNormal
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_TheTemperatureOfMoltenAluminumInTheProcessIsNormal") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        #endregion 预检测项

        #endregion 页面属性

        #region 定义页面执行命令
        /// <summary>
        /// 跳转页面名称
        /// </summary>
        public DelegateCommand GoToPageCommand { get; set; }
        /// <summary>
        /// 重量清零命令
        /// </summary>
        public DelegateCommand ClearWeightCommand { get; set; }
        /// <summary>
        /// 显示模态窗体
        /// </summary>
        public DelegateCommand ShowModalPanelCommand { get; set; }

        #endregion 定义页面执行命令

        #region 线程对象
        /// <summary>
        /// 标签值变化监听线程
        /// </summary>
        private Thread tagInfoSyncThread = null;
        #endregion 线程对象

        #region 方法
        /// <summary>
        /// 构造方法
        /// </summary>
        public LaunderPageViewModel()
        {
            // 初始化命令
            initCommand();
            // 初始化线程
            initThread();
            // 消息通道注册
            initMessenger();
        }

        /// <summary>
        /// 页面切换
        /// </summary>
        /// <param name="obj"></param>
        private void changeTabHandler(object obj)
        {
            Messenger.Default.Send<string>(obj.ToString(), "GoToPage");
        }

        /// <summary>
        /// 执行动作
        /// </summary>
        /// <param name="hashSet"></param>
        private void DoChanged(HashSet<Control> hashSet)
        {
            //遍历返回的控件信息刷新对应的控件
            foreach (Control item in hashSet)
            {
                RaisePropertyChanged(item.ControlName);
            }
        }

        /// <summary>
        /// 显示弹出操作面板
        /// BUG 一号激光液位计 位调用该方法
        /// </summary>
        /// <param name="obj"></param>
        private void showModalPanelHandler(object obj)
        {
            string param = obj.ToString();
            switch (param)
            {
                case "Button_LaunderBaffle1"://如果是一号挡板
                    WindowManager.ShowModalPanel("LaunderBafflePanel", showPageTitle, param);
                    break;
                case "Button_LaunderBaffle2"://如果是二号挡板
                    WindowManager.ShowModalPanel("LaunderBafflePanel", showPageTitle, param);
                    break;
                case "Button_AuroraLevelGauge1"://如果是一号激光液位计
                    WindowManager.ShowModalPanel("AuroraLevelGaugePanel", showPageTitle, param);
                    break;
                case "Button_AuroraLevelGauge2"://如果是二号激光液位计
                    WindowManager.ShowModalPanel("AuroraLevelGaugePanel", showPageTitle, param);
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 重量清零命令处理器
        /// </summary>
        /// <param name="obj"></param>
        private void clearWeightHandler(object obj)
        {
            BusinessCmd setTagValueMsg = new BusinessCmd
            {
                Guid = Guid.NewGuid().ToString(),
                BusinessCmdCode = 3,
                TagId = TagTool.GetTagIdByValueByFormNameAndControlName(showPageTitle, obj.ToString()),
                TagValue = "true"
            };
            // 发送消息
            if (KafkaHelper.SendGatewayBusinessCmd(setTagValueMsg))
            {
                RaisePropertyChanged("Label_Weight_PV1");
            }
        }

        /// <summary>
        /// 初始化命令
        /// </summary>
        private void initCommand()
        {
            // 页面跳转
            GoToPageCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(changeTabHandler)
            };
            // 页面操作按钮触发事件
            ShowModalPanelCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(showModalPanelHandler)
            };
            // 重量清零
            ClearWeightCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(clearWeightHandler)
            };
        }

        /// <summary>
        /// 初始化线程
        /// </summary>
        private void initThread()
        {
            // 标签值变化监听线程
            tagInfoSyncThread = new Thread(syncThreadFunc);
            tagInfoSyncThread.SetApartmentState(ApartmentState.STA);
            tagInfoSyncThread.IsBackground = true;
            tagInfoSyncThread.Start();
        }

        /// <summary>
        /// 同步标签数据方法
        /// </summary>
        private void syncThreadFunc()
        {

            // 创建消费者对象
            IConsumer<string, object> KafkaConsumer = KafkaHelper.GetConsumer();
            while (true)
            {
                if (SystemConfig.systemState == "预检测" || SystemConfig.systemState == "可见许可")
                {
                    PreDetectionVisibility = Visibility.Visible;
                }
                else
                {
                    PreDetectionVisibility = Visibility.Hidden;
                }
                // 网络中断不进行消费监听
                if (SystemConfig.SystemStatus == "网络中断")
                {
                    Thread.Sleep(1000);
                    continue;
                }
                if (ThreadController.RoundBarLaunderThreadState)
                {
                    //开始消费
                    var result = KafkaConsumer.Consume();
                    if (result != null)
                    {
                        //手动提交
                        KafkaConsumer.Commit(result);
                        //获取消息内容
                        string tagId = result.Message.Value.ToString();
                        HashSet<Control> hashSet = KafkaHelper.UpdateCurrentUserTagValue(Int32.Parse(tagId), KafkaHelper.GetTagValueByKey(tagId.ToString()), showPageTitle);
                        if (hashSet != null)
                        {
                            DoChanged(hashSet);
                        }
                    }
                }
                Thread.Sleep(10);
            }
        }

        /// <summary>
        /// 消息通道注册
        /// ViewModel之间数据通信使用，整个项目全局唯一
        /// </summary>
        private void initMessenger()
        {
            //刷新控件,注：此处没用上
            Messenger.Default.Register<string>(this, "LaunderPageRefreshControl", (message) =>
            {
                RaisePropertyChanged(message);
            });
        }
        #endregion 方法














    }
}
